package com.firefly.admin.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefly.admin.common.constant.Constants;
import com.firefly.admin.common.enums.ResultCodeEnum;
import com.firefly.admin.common.vo.Result;
import com.firefly.admin.system.service.FySystemRoleMenuService;
import com.firefly.admin.system.service.FySystemRoleService;
import com.firefly.admin.system.service.FySystemUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.firefly.admin.system.entity.FySystemRole;
import com.firefly.admin.system.entity.FySystemRoleMenu;
import com.firefly.admin.system.entity.FySystemUserRole;
import com.firefly.admin.system.mapper.FySystemRoleMapper;
import com.firefly.admin.system.vo.SystemRoleAssignMenusVo;
import com.firefly.admin.system.vo.SystemRoleQueryVo;
import com.firefly.admin.system.vo.SystemRoleStatusUpdateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FySystemRoleServiceImpl implements FySystemRoleService {
    @Autowired
    private FySystemRoleMapper fySystemRoleMapper;

    @Autowired
    private FySystemRoleMenuService fySystemRoleMenuService;

    @Autowired
    private FySystemUserRoleService fySystemUserRoleService;


    @Override
    public List<FySystemRole> getRoleList(Long userId) {
        return fySystemRoleMapper.getRoleList(userId);
    }

    /**
     * 分页查询系统角色接口
     *
     * @param systemRoleQueryVo 分页查询参数
     * @return 分页列表
     */
    @Override
    public Result<Page<FySystemRole>> getSystemRoleList(SystemRoleQueryVo systemRoleQueryVo) {
        log.info("###########FySystemRoleServiceImpl getSystemRoleList param = {}", JSONObject.toJSONString(systemRoleQueryVo));
        LambdaQueryWrapper<FySystemRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(systemRoleQueryVo.getRoleName()), FySystemRole::getRoleName, systemRoleQueryVo.getRoleName());
        queryWrapper.eq(StringUtils.isNotBlank(systemRoleQueryVo.getRoleStatus()), FySystemRole::getRoleStatus, systemRoleQueryVo.getRoleStatus());
        queryWrapper.eq(FySystemRole::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        queryWrapper.orderByDesc(FySystemRole::getRoleId);
        Page<FySystemRole> page = new Page<>(systemRoleQueryVo.getPage(), systemRoleQueryVo.getLimit());
        Page<FySystemRole> systemRolePage = fySystemRoleMapper.selectPage(page, queryWrapper);
        return Result.success(systemRolePage);
    }

    /**
     * 获取系统角色信息接口
     *
     * @param roleId 角色ID
     * @return 角色信息
     */
    @Override
    public Result<FySystemRole> getSystemRole(Long roleId) {
        if (roleId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemRole fySystemRole = fySystemRoleMapper.selectById(roleId);
        if (fySystemRole == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_NOT_FOUND);
        }
        return Result.success(fySystemRole);
    }

    /**
     * 系统角色信息新增接口
     *
     * @param fySystemRole 角色信息
     * @return 操作结果
     */
    @Override
    public Result<FySystemRole> add(FySystemRole fySystemRole) {
        if (fySystemRole == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        ResultCodeEnum resultCodeEnum = checkRoleParam(fySystemRole);
        if (resultCodeEnum != null) {
            return Result.getResult(resultCodeEnum);
        }
        int rows = fySystemRoleMapper.insert(fySystemRole);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.ADD_EXCEPTION);
        }
        return Result.success(fySystemRole);
    }

    private ResultCodeEnum checkRoleParam(FySystemRole fySystemRole) {
        String roleName = fySystemRole.getRoleName();
        if (StringUtils.isBlank(roleName)) {
            return ResultCodeEnum.SYSTEM_ROLE_NAME_NOT_NULL;
        }
        Long roleId = fySystemRole.getRoleId();
        LambdaQueryWrapper<FySystemRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemRole::getRoleName, roleName);
        queryWrapper.eq(FySystemRole::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        List<FySystemRole> systemRoleList = fySystemRoleMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemRoleList)) {
            if (roleId == null) {
                //新增
                return ResultCodeEnum.SYSTEM_ROLE_NAME_EXIST;
            }
            //编辑
            for (FySystemRole systemRole : systemRoleList) {
                if (systemRole.getRoleId() != roleId.longValue()) {
                    return ResultCodeEnum.SYSTEM_ROLE_NAME_EXIST;
                }
            }
        }
        String roleStatus = fySystemRole.getRoleStatus();
        if (roleId == null && StringUtils.isBlank(roleStatus)) {
            fySystemRole.setRoleStatus(Constants.Status.ENABLE);
        }
        return null;
    }

    /**
     * 系统角色信息编辑接口
     *
     * @param fySystemRole 角色信息
     * @return 操作结果
     */
    @Override
    public Result<FySystemRole> update(FySystemRole fySystemRole) {
        if (fySystemRole == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long roleId = fySystemRole.getRoleId();
        if (roleId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemRole systemRole = fySystemRoleMapper.selectById(roleId);
        if (systemRole == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_NOT_FOUND);
        }
        ResultCodeEnum resultCodeEnum = checkRoleParam(fySystemRole);
        if (resultCodeEnum != null) {
            return Result.getResult(resultCodeEnum);
        }
        int rows = fySystemRoleMapper.updateById(fySystemRole);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        return Result.success(fySystemRole);
    }

    /**
     * 系统角色信息删除接口
     *
     * @param roleId 角色ID
     * @return 操作结果
     */
    @Override
    public Result<String> delete(Long roleId) {
        if (roleId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemRole fySystemRole = fySystemRoleMapper.selectById(roleId);
        if (fySystemRole == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_NOT_FOUND);
        }
        List<FySystemUserRole> fySystemUserRoleList = fySystemUserRoleService.selectByRoleId(roleId);
        if (!CollectionUtils.isEmpty(fySystemUserRoleList)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_USING);
        }
        fySystemRole.setDeleteFlag(Constants.DeleteFlag.DELETE);
        int rows = fySystemRoleMapper.updateById(fySystemRole);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.DELETE_EXCEPTION);
        }
        return Result.success();
    }

    /**
     * 系统角色分配菜单权限接口
     *
     * @param systemRoleAssignMenusVo 角色权限信息
     * @return 操作结果
     */
    @Override
    @Transient
    public Result<String> assignMenus(SystemRoleAssignMenusVo systemRoleAssignMenusVo) {
        if (systemRoleAssignMenusVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long roleId = systemRoleAssignMenusVo.getRoleId();
        if (roleId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemRole fySystemRole = fySystemRoleMapper.selectById(roleId);
        if (fySystemRole == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_NOT_FOUND);
        }
        //删除原有菜单权限
        List<FySystemRoleMenu> roleMenuList = fySystemRoleMenuService.selectByRoleId(roleId);
        if (!CollectionUtils.isEmpty(roleMenuList)) {
            int rows = fySystemRoleMenuService.deleteByRoleId(roleId);
            if (rows <= 0) {
                return Result.getResult(ResultCodeEnum.DELETE_ROLE_MENUS_EXCEPTION);
            }
        }
        String menuIds = systemRoleAssignMenusVo.getMenuIds();
        if (StringUtils.isBlank(menuIds)) {
            log.warn("FySystemRoleServiceImpl assignMenus menuIdS size = 0");
            return Result.success();
        }
        //菜单
        List<Long> menuIdList = new ArrayList<>();
        Arrays.asList(menuIds.split(StringPool.COMMA)).forEach(id -> menuIdList.add(Long.valueOf(id)));
        int saveRows = fySystemRoleMenuService.saveRoleMenus(roleId, menuIdList);
        if (saveRows <= 0) {
            return Result.getResult(ResultCodeEnum.ADD_USER_ROLES_EXCEPTION);
        }
        return Result.success();
    }

    /**
     * 系统角色状态编辑接口
     *
     * @param systemRoleStatusUpdateVo 状态信息
     * @return 操作结果
     */
    @Override
    public Result<FySystemRole> updateStatus(SystemRoleStatusUpdateVo systemRoleStatusUpdateVo) {
        if (systemRoleStatusUpdateVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long roleId = systemRoleStatusUpdateVo.getRoleId();
        if (roleId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemRole fySystemRole = fySystemRoleMapper.selectById(roleId);
        if (fySystemRole == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_NOT_FOUND);
        }
        String roleStatus = systemRoleStatusUpdateVo.getRoleStatus();
        if (StringUtils.isBlank(roleStatus)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_STATUS_NOT_NULL);
        }
        fySystemRole.setRoleStatus(roleStatus);
        int rows = fySystemRoleMapper.updateById(fySystemRole);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        return Result.success(fySystemRole);
    }

    /**
     * 获取有所可用角色
     *
     * @return 角色列表
     */
    @Override
    public Result<List<FySystemRole>> getAllUsableRoleList() {
        LambdaQueryWrapper<FySystemRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemRole::getRoleStatus, Constants.Status.ENABLE);
        List<FySystemRole> systemRoleList = fySystemRoleMapper.selectList(queryWrapper);
        return Result.success(systemRoleList);
    }

    /**
     * 系统角色名称校验接口
     *
     * @param roleName 角色名称
     * @param roleId   角色ID
     * @return 校验结果
     */
    @Override
    public Result<String> roleNameCheck(String roleName, Long roleId) {
        if (StringUtils.isBlank(roleName)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_ROLE_NAME_NOT_NULL);
        }
        LambdaQueryWrapper<FySystemRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemRole::getRoleName, roleName);
        List<FySystemRole> systemRoleList = fySystemRoleMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemRoleList)) {
            if (roleId == null) {
                //新增
                return Result.success(ResultCodeEnum.SYSTEM_ROLE_NAME_EXIST.getMsg());
            } else {
                //编辑
                for (FySystemRole systemRole : systemRoleList) {
                    if (roleId.longValue() != systemRole.getRoleId().longValue()) {
                        return Result.success(ResultCodeEnum.SYSTEM_ROLE_NAME_EXIST.getMsg());
                    }
                }
            }
        }
        return Result.success();
    }


    /**
     * 通过角色ID获取菜单接口
     *
     * @param roleId 角色ID
     * @return 查询结果
     */
    @Override
    public Result<List<Long>> getRoleMenus(Long roleId) {
        if (roleId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        List<FySystemRoleMenu> roleMenuList = fySystemRoleMenuService.selectByRoleId(roleId);
        List<Long> menuIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roleMenuList)) {
            menuIds = roleMenuList.stream().map(FySystemRoleMenu::getMenuId).collect(Collectors.toList());
        }
        return Result.success(menuIds);
    }
}
